package com.argrace.smart.activity.devicerelation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.activity.DeviceControl_KaiguanActivity;
import com.argrace.smart.activity.DeviceModifyActivity;
import com.argrace.smart.activity.QingJingListActivity;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.ui.DrawableSwitch;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.utils;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/3/5.
 */

public class DeviceRelation_KaiGuanActivity extends BaseActivity {
    private ImageView img;
    private DrawableSwitch kaiguan_1, kaiguan_2, kaiguan_3;
    private DrawableSwitch kaiguan_4, kaiguan_5, kaiguan_6;
    private TextView text1, text2, text3, text4, text5, text6;
    MineZigBeeDeviceListEntity bean;
    private LinearLayout ll1, ll2, ll3, ll4, ll5, ll6;
    private Map<String, String> model_imgurl = new HashMap<>();
    private int type = ConstantConfigure.TYPE_CONTROL;
    private String name;
    //此处开始修改为关联设备增加的属性
    String uuid, model;
    LinearLayout relationdevice_ll;
    TextView relationdevice_text;
    private int qingJingTable_id = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_kaiguan);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        uuid = bean.getUuid();
        model = bean.getModel();
        setTitle(true, false, "关联设备");
        showRight(true, R.mipmap.head_title_tick);
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        setView();
        getDeviceDetailInfo();
    }

    private void save() {
        //开关0关闭,1开启
        LocalDb_RelationDeviceTable relationDeviceTable = new LocalDb_RelationDeviceTable();
        relationDeviceTable.setUuid(uuid);
        relationDeviceTable.setModel(model);
        Map<String, String> trigger_condition = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        if (model.equals(ConstantConfigure.MODEL_SANWEIDUOKONG)) {
            if (kaiguan_1.isSwitchOn()) {
                sb.append("\"Switch_1\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"Switch_1\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            if (kaiguan_2.isSwitchOn()) {
                sb.append("\"Switch_2\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"Switch_2\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            if (kaiguan_2.isSwitchOn()) {
                sb.append("\"Switch_3\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"Switch_3\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
        }
        if (model.equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)) {
            if (kaiguan_1.isSwitchOn()) {
                sb.append("\"Switch_1\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"Switch_1\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            if (kaiguan_2.isSwitchOn()) {
                sb.append("\"Switch_2\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"Switch_2\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
        }
        if (model.equals(ConstantConfigure.MODEL_YIWEIDUOKONG)) {
            if (kaiguan_1.isSwitchOn()) {
                sb.append("\"Switch\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"Switch\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
        }
        sb.append("}");
        relationDeviceTable.setTrigger_condition(sb.toString());
        relationDeviceTable.setQingJingTable_id(qingJingTable_id);
        List<LocalDb_RelationDeviceTable> lists = DataSupport.where("uuid = ?", uuid).find(LocalDb_RelationDeviceTable.class);
        boolean is_same = false;
        int table_id = 0;
        if (lists != null && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getTrigger_condition() != null && lists.get(i).getTrigger_condition().equals(relationDeviceTable.getTrigger_condition())) {
                    is_same = true;
                    table_id = lists.get(i).getId();
                }
            }
        }
        //如果相等则updata
        if (is_same) {
            relationDeviceTable.update(table_id);
        } else {
            relationDeviceTable.save();
        }
        finish();
        toastActBtm("保存成功");
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        kaiguan_1 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan_kaiguan1);
        kaiguan_2 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan_kaiguan2);
        kaiguan_3 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan_kaiguan3);
        kaiguan_4 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan_kaiguan4);
        kaiguan_5 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan_kaiguan5);
        kaiguan_6 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_kaiguan_kaiguan6);
        text1 = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan_text1);
        text2 = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan_text2);
        text3 = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan_text3);
        text4 = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan_text4);
        text5 = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan_text5);
        text6 = (TextView) findViewById(R.id.activity_devicecontrol_kaiguan_text6);
        ll1 = (LinearLayout) findViewById(R.id.activity_devicecontrol_kaiguan_ll1);
        ll2 = (LinearLayout) findViewById(R.id.activity_devicecontrol_kaiguan_ll2);
        ll3 = (LinearLayout) findViewById(R.id.activity_devicecontrol_kaiguan_ll3);
        ll4 = (LinearLayout) findViewById(R.id.activity_devicecontrol_kaiguan_ll4);
        ll5 = (LinearLayout) findViewById(R.id.activity_devicecontrol_kaiguan_ll5);
        ll6 = (LinearLayout) findViewById(R.id.activity_devicecontrol_kaiguan_ll6);
        //modify for relationdevice start
        relationdevice_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_ll);
        relationdevice_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_text);
        relationdevice_ll.setVisibility(View.VISIBLE);
        relationdevice_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeviceRelation_KaiGuanActivity.this, QingJingListActivity.class);
                startActivityForResult(intent, ConstantConfigure.DEFAULT_ZERO);
            }
        });
        //modify for relationdevice end
        String imgurl = null;
        if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)) {
            imgurl = ConstantConfigure.IMGURL_SANWEIQINGCHUDUOKONG_00501E13;
            ll1.setVisibility(View.VISIBLE);
            ll2.setVisibility(View.VISIBLE);
            ll3.setVisibility(View.VISIBLE);
            ll4.setVisibility(View.GONE);
            ll5.setVisibility(View.GONE);
            ll6.setVisibility(View.GONE);
            kaiguan_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = kaiguan_1.isSwitchOn() ? 0 : 1;
                    kaiguan_1.setSwitchOn(!kaiguan_1.isSwitchOn());
                    kaiguan_1.invalidate();
                }
            });
            kaiguan_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = kaiguan_2.isSwitchOn() ? 0 : 1;
                    kaiguan_2.setSwitchOn(!kaiguan_2.isSwitchOn());
                    kaiguan_2.invalidate();
                }
            });
            kaiguan_3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = kaiguan_3.isSwitchOn() ? 0 : 1;
                    kaiguan_3.setSwitchOn(!kaiguan_3.isSwitchOn());
                    kaiguan_3.invalidate();
                }
            });
        }

        if (bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)) {
            imgurl = ConstantConfigure.IMGURL_LIANGWEIQINGCHUDUOKONG_00501d7e;
            ll1.setVisibility(View.VISIBLE);
            ll2.setVisibility(View.VISIBLE);
            ll3.setVisibility(View.GONE);
            ll4.setVisibility(View.GONE);
            ll5.setVisibility(View.GONE);
            ll6.setVisibility(View.GONE);
            kaiguan_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = kaiguan_1.isSwitchOn() ? 0 : 1;
                    kaiguan_1.setSwitchOn(!kaiguan_1.isSwitchOn());
                    kaiguan_1.invalidate();
                }
            });
            kaiguan_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = kaiguan_2.isSwitchOn() ? 0 : 1;
                    kaiguan_2.setSwitchOn(!kaiguan_2.isSwitchOn());
                    kaiguan_2.invalidate();
                }
            });
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_YIWEIDUOKONG)) {
            imgurl = ConstantConfigure.IMGURL_YIWEIQINGCHUDUOKONG_00501E11;
            ll1.setVisibility(View.VISIBLE);
            ll2.setVisibility(View.GONE);
            ll3.setVisibility(View.GONE);
            ll4.setVisibility(View.GONE);
            ll5.setVisibility(View.GONE);
            ll6.setVisibility(View.GONE);
            kaiguan_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = kaiguan_1.isSwitchOn() ? 0 : 1;
                    kaiguan_1.setSwitchOn(!kaiguan_1.isSwitchOn());
                    kaiguan_1.invalidate();
                }
            });
        }


        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }
    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);

                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }


    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }

        if (bean.getModel().equals(ConstantConfigure.MODEL_YIWEIDUOKONG)) {
            Key_ValueEntity bean = JSON.parseObject(obj.getString("Switch"), Key_ValueEntity.class);
            //0关闭，1开启
            if (bean != null && bean.getValue().equals("0")) {
                kaiguan_1.setSwitchOn(false);
            } else {
                kaiguan_1.setSwitchOn(true);
            }
            kaiguan_1.invalidate();
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)) {
            Key_ValueEntity bean1 = JSON.parseObject(obj.getString("Switch_1"), Key_ValueEntity.class);
            //0关闭，1开启
            if (bean1 != null && bean1.getValue().equals("0")) {
                kaiguan_1.setSwitchOn(false);
            } else {
                kaiguan_1.setSwitchOn(true);
            }
            kaiguan_1.invalidate();
            Key_ValueEntity bean2 = JSON.parseObject(obj.getString("Switch_2"), Key_ValueEntity.class);
            //0关闭，1开启
            if (bean2 != null && bean2.getValue().equals("0")) {
                kaiguan_2.setSwitchOn(false);
            } else {
                kaiguan_2.setSwitchOn(true);
            }
            kaiguan_2.invalidate();
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)) {
            Key_ValueEntity bean1 = JSON.parseObject(obj.getString("Switch_1"), Key_ValueEntity.class);
            //0关闭，1开启
            if (bean1 != null && bean1.getValue().equals("0")) {
                kaiguan_1.setSwitchOn(false);
            } else {
                kaiguan_1.setSwitchOn(true);
            }
            kaiguan_1.invalidate();
            Key_ValueEntity bean2 = JSON.parseObject(obj.getString("Switch_2"), Key_ValueEntity.class);
            //0关闭，1开启
            if (bean2 != null && bean2.getValue().equals("0")) {
                kaiguan_2.setSwitchOn(false);
            } else {
                kaiguan_2.setSwitchOn(true);
            }
            kaiguan_2.invalidate();
            Key_ValueEntity bean3 = JSON.parseObject(obj.getString("Switch_3"), Key_ValueEntity.class);
            //0关闭，1开启
            if (bean3 != null && bean3.getValue().equals("0")) {
                kaiguan_3.setSwitchOn(false);
            } else {
                kaiguan_3.setSwitchOn(true);
            }
            kaiguan_3.invalidate();
        }

        if (bean.getModel().equals(ConstantConfigure.MODEL_CHANGJINGKAIGUAN)) {
            Key_ValueEntity bean1 = JSON.parseObject(obj.getString("KeyFobValue"), Key_ValueEntity.class);
            if (bean1.getValue().equals("1")) {
                kaiguan_1.setSwitchOn(true);
                kaiguan_2.setSwitchOn(false);
                kaiguan_3.setSwitchOn(false);
                kaiguan_4.setSwitchOn(false);
                kaiguan_5.setSwitchOn(false);
                kaiguan_6.setSwitchOn(false);
            }
            if (bean1.getValue().equals("2")) {
                kaiguan_1.setSwitchOn(false);
                kaiguan_2.setSwitchOn(true);
                kaiguan_3.setSwitchOn(false);
                kaiguan_4.setSwitchOn(false);
                kaiguan_5.setSwitchOn(false);
                kaiguan_6.setSwitchOn(false);
            }
            if (bean1.getValue().equals("3")) {
                kaiguan_3.setSwitchOn(true);
                kaiguan_2.setSwitchOn(false);
                kaiguan_1.setSwitchOn(false);
                kaiguan_4.setSwitchOn(false);
                kaiguan_5.setSwitchOn(false);
                kaiguan_6.setSwitchOn(false);
            }
            if (bean1.getValue().equals("4")) {
                kaiguan_4.setSwitchOn(true);
                kaiguan_2.setSwitchOn(false);
                kaiguan_3.setSwitchOn(false);
                kaiguan_1.setSwitchOn(false);
                kaiguan_5.setSwitchOn(false);
                kaiguan_6.setSwitchOn(false);
            }
            if (bean1.getValue().equals("5")) {
                kaiguan_5.setSwitchOn(true);
                kaiguan_2.setSwitchOn(false);
                kaiguan_3.setSwitchOn(false);
                kaiguan_4.setSwitchOn(false);
                kaiguan_1.setSwitchOn(false);
                kaiguan_6.setSwitchOn(false);
            }
            if (bean1.getValue().equals("6")) {
                kaiguan_6.setSwitchOn(true);
                kaiguan_2.setSwitchOn(false);
                kaiguan_3.setSwitchOn(false);
                kaiguan_4.setSwitchOn(false);
                kaiguan_5.setSwitchOn(false);
                kaiguan_1.setSwitchOn(false);
            }
            kaiguan_6.invalidate();
            kaiguan_2.invalidate();
            kaiguan_3.invalidate();
            kaiguan_4.invalidate();
            kaiguan_5.invalidate();
            kaiguan_1.invalidate();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("name");
            qingJingTable_id = data.getIntExtra("id", 0);
            relationdevice_text.setText(name);
        }
    }
}
